package org.osgroup.service;

import org.osgroup.dto.*;
import org.osgroup.project.FoodStreet;
import org.osgroup.project.Restaurant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 订单服务类 - 管理所有订单
 */
@Service
public class OrderService {
    
    @Autowired
    private FoodStreetService foodStreetService;
    
    private final Map<String, FoodOrder> orders = new ConcurrentHashMap<>();
    private final AtomicLong orderCounter = new AtomicLong(1);
    
    /**
     * 提交订单
     */
    public OrderSubmitResponse submitOrder(OrderSubmitRequest request) {
        try {
            // 生成订单号
            String orderNumber = generateOrderNumber();
            
            // 创建订单对象
            FoodOrder order = new FoodOrder();
            order.setOrderNumber(orderNumber);
            order.setCustomerName(request.getCustomerName());
            order.setItems(request.getItems());
            order.setTotalAmount(request.getTotalAmount());
            order.setOrderTime(LocalDateTime.now());
            order.setStatus("pending");
            order.setRestaurant(request.getRestaurant());
            
            // 保存订单
            orders.put(orderNumber, order);
            
            // 实际下单到餐厅
            List<String> failedItems = new ArrayList<>();
            FoodStreet foodStreet = foodStreetService.getFoodStreet();
            if (foodStreet != null && request.getRestaurant() != null) {
                Restaurant restaurant = findRestaurantByName(request.getRestaurant(), foodStreet);
                if (restaurant != null && restaurant.isOpen()) {
                    // 计算订单总数量
                    int totalItemCount = 0;
                    for (OrderItem item : request.getItems()) {
                        totalItemCount += item.getQuantity();
                    }
                    final int expectedMealCount = totalItemCount;
                    
                    // 🔥 下单前检查队列剩余容量
                    int currentQueueSize = restaurant.getOrderQueueSize();
                    int availableCapacity = restaurant.getOrderQueueCapacity() - currentQueueSize;
                    
                    if (totalItemCount > availableCapacity) {
                        // 订单数量超过剩余容量,直接拒绝
                        OrderSubmitResponse errorResponse = new OrderSubmitResponse();
                        errorResponse.setCode(503);
                        errorResponse.setMessage(String.format(
                            "订单队列容量不足！当前队列: %d/%d，剩余容量: %d，您的订单: %d",
                            currentQueueSize, restaurant.getOrderQueueCapacity(), availableCapacity, totalItemCount
                        ));
                        errorResponse.setOrderNumber(orderNumber);
                        return errorResponse;
                    }
                    
                    // 为每个订单项实际下单(非阻塞方式)
                    int successCount = 0;
                    for (OrderItem item : request.getItems()) {
                        try {
                            // 根据菜品名称找到对应的菜单项ID
                            String itemId = findMenuItemId(restaurant, item.getName());
                            if (itemId != null) {
                                // 创建虚拟游客对象用于下单
                                org.osgroup.visitor.BaseVisitor visitor = new org.osgroup.visitor.BaseVisitor();
                                visitor.setName(request.getCustomerName());
                                
                                // 下单多份(根据quantity) - 使用非阻塞方式
                                for (int i = 0; i < item.getQuantity(); i++) {
                                    Restaurant.Order placedOrder = restaurant.tryPlaceOrder(visitor, itemId);
                                    if (placedOrder == null) {
                                        // 订单队列已满,无法下单
                                        failedItems.add(item.getName() + "(队列已满)");
                                        System.out.println("⚠️ 订单队列已满,无法下单: " + item.getName());
                                        break;
                                    } else {
                                        successCount++;
                                    }
                                }
                                
                                if (!failedItems.contains(item.getName() + "(队列已满)")) {
                                    System.out.println("✅ 已在 " + request.getRestaurant() + " 下单: " + 
                                                     item.getName() + " x" + item.getQuantity());
                                }
                            } else {
                                failedItems.add(item.getName() + "(菜品不存在)");
                                System.out.println("⚠️ 菜品不存在: " + item.getName());
                            }
                        } catch (Exception e) {
                            failedItems.add(item.getName() + "(系统错误)");
                            System.out.println("❌ 下单失败: " + item.getName() + " - " + e.getMessage());
                        }
                    }
                    
                    // 检查是否所有订单都失败了
                    if (successCount == 0) {
                        // 所有订单都失败,返回错误
                        OrderSubmitResponse errorResponse = new OrderSubmitResponse();
                        errorResponse.setCode(503);
                        errorResponse.setMessage("订单队列已满,请稍后再试");
                        errorResponse.setOrderNumber(orderNumber);
                        return errorResponse;
                    }
                    
                    // 如果有失败的订单项,更新订单状态
                    if (!failedItems.isEmpty()) {
                        order.setStatus("partial"); // 部分成功
                        System.out.println("⚠️ 部分菜品下单失败: " + String.join(", ", failedItems));
                    }
                    
                    // 🔥 启动取餐线程,自动取走制作完成的餐品
                    final String finalOrderNumber = orderNumber;
                    final Restaurant finalRestaurant = restaurant;
                    final int finalSuccessCount = successCount; // 只取成功下单的数量
                    Thread pickupThread = new Thread(() -> {
                        try {
                            int pickedCount = 0;
                            org.osgroup.visitor.BaseVisitor visitor = new org.osgroup.visitor.BaseVisitor();
                            visitor.setName(request.getCustomerName());
                            
                            // 取餐,直到取完所有成功下单的餐品
                            while (pickedCount < finalSuccessCount) {
                                Restaurant.Meal meal = finalRestaurant.consumeMeal(visitor);
                                if (meal != null) {
                                    pickedCount++;
                                    System.out.println("🍽️  [订单 " + finalOrderNumber + "] " + 
                                                     visitor.getName() + " 取到 " + meal.getMealName() + 
                                                     " (" + pickedCount + "/" + finalSuccessCount + ")");
                                }
                                
                                // 短暂休眠避免CPU空转
                                Thread.sleep(100);
                            }
                            
                            // 所有餐品已取完,更新订单状态
                            FoodOrder completedOrder = orders.get(finalOrderNumber);
                            if (completedOrder != null) {
                                completedOrder.setStatus("completed");
                                System.out.println("✅ [订单 " + finalOrderNumber + "] 所有餐品已取完");
                            }
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            System.out.println("⚠️ 取餐线程被中断: " + finalOrderNumber);
                        }
                    });
                    pickupThread.setDaemon(true);
                    pickupThread.setName("PickupThread-" + orderNumber);
                    pickupThread.start();
                    
                } else {
                    System.out.println("⚠️ 餐厅未营业或不存在: " + request.getRestaurant());
                }
            }
            
            // 构建响应
            OrderSubmitResponse response = new OrderSubmitResponse();
            response.setCode(200);
            response.setMessage("订单提交成功");
            response.setOrderNumber(orderNumber);
            response.setTotalAmount(request.getTotalAmount());
            
            return response;
            
        } catch (Exception e) {
            OrderSubmitResponse response = new OrderSubmitResponse();
            response.setCode(500);
            response.setMessage("订单提交失败: " + e.getMessage());
            return response;
        }
    }
    
    /**
     * 获取订单历史
     */
    public List<FoodOrder> getOrderHistory(String customerName) {
        List<FoodOrder> history = new ArrayList<>();
        for (FoodOrder order : orders.values()) {
            if (customerName == null || customerName.equals(order.getCustomerName())) {
                history.add(order);
            }
        }
        // 按时间倒序排序
        history.sort((o1, o2) -> o2.getOrderTime().compareTo(o1.getOrderTime()));
        return history;
    }
    
    /**
     * 获取订单详情
     */
    public FoodOrder getOrderDetails(String orderNumber) {
        return orders.get(orderNumber);
    }
    
    /**
     * 取消订单
     */
    public OrderCancelResponse cancelOrder(String orderNumber) {
        FoodOrder order = orders.get(orderNumber);
        
        OrderCancelResponse response = new OrderCancelResponse();
        
        if (order == null) {
            response.setCode(404);
            response.setMessage("订单不存在");
            return response;
        }
        
        if ("completed".equals(order.getStatus()) || "cancelled".equals(order.getStatus())) {
            response.setCode(400);
            response.setMessage("订单已完成或已取消,无法再次取消");
            return response;
        }
        
        order.setStatus("cancelled");
        
        response.setCode(200);
        response.setMessage("订单取消成功");
        response.setOrderNumber(orderNumber);
        
        return response;
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNumber() {
        String date = LocalDateTime.now().toString().substring(0, 10).replace("-", "");
        long seq = orderCounter.getAndIncrement();
        return String.format("ORD%s%03d", date, seq);
    }
    
    /**
     * 根据名称查找餐厅
     */
    private Restaurant findRestaurantByName(String name, FoodStreet foodStreet) {
        if (foodStreet == null) return null;
        for (Restaurant r : foodStreet.getAllRestaurants()) {
            if (r.getRestaurantName().equals(name)) {
                return r;
            }
        }
        return null;
    }
    
    /**
     * 根据菜品名称查找菜单项ID
     */
    private String findMenuItemId(Restaurant restaurant, String itemName) {
        if (restaurant == null || itemName == null) return null;
        
        List<Restaurant.MenuItem> menuItems = restaurant.getMenuItems();
        for (Restaurant.MenuItem menuItem : menuItems) {
            if (itemName.equals(menuItem.getItemName())) {
                return menuItem.getItemId();
            }
        }
        return null;
    }
}
